package com.kaizeli.website.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaizeli.website.context.BaseContext;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * JWT拦截器
 * 用于验证用户Token的有效性
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置CORS响应头
        setCorsHeaders(request, response);
        
        // 处理OPTIONS预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = null;
        
        // 1. 从Authorization头获取Token
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        }
        
        // 2. 如果Header中没有，尝试从请求参数获取
        if (token == null) {
            token = request.getParameter("token");
        }

        // 3. 验证Token是否存在（暂时设为非必填）
        if (token == null || token.trim().isEmpty()) {
            log.info("请求未携带Token，允许通过，请求路径：{}", request.getRequestURI());
            return true;
        }

        try {
            // 4. 验证Token格式是否有效
            Claims claims = JwtUtil.getClaimsFromToken(token);
            String username = claims.getSubject();

            // 5. 从数据库验证Token是否有效
            String sql = 
                "SELECT id, username, administrator, is_token_valid, token_expires_at " +
                "FROM users " +
                "WHERE current_token = ? AND username = ?";
            
            Map<String, Object> user = jdbcTemplate.queryForMap(sql, token, username);

            // 6. 检查Token是否被标记为无效
            Object tokenValidObj = user.get("is_token_valid");
            boolean isTokenValid;
            if (tokenValidObj instanceof Boolean) {
                isTokenValid = (Boolean) tokenValidObj;
            } else if (tokenValidObj instanceof Number) {
                isTokenValid = ((Number) tokenValidObj).intValue() == 1;
            } else {
                isTokenValid = false;
            }

            if (!isTokenValid) {
                log.warn("Token已失效，用户：{}", username);
                sendErrorResponse(response, 401, "登录已过期，请重新登录");
                return false;
            }

            // 7. 检查Token是否过期（数据库时间）
            Object expiresAt = user.get("token_expires_at");
            if (expiresAt == null) {
                log.warn("Token过期时间不存在，用户：{}", username);
                sendErrorResponse(response, 401, "登录已过期，请重新登录");
                return false;
            }

            // 8. 将用户信息存储到请求属性中，供Controller使用
            request.setAttribute("userId", user.get("id"));
            request.setAttribute("username", username);
            request.setAttribute("administrator", user.get("administrator"));
            
            // 9. 设置ThreadLocal，供AutoFillPlugin使用
            BaseContext.setCurrentId(user.get("id").toString());
            BaseContext.setPermissions(user.get("administrator").toString());

            log.debug("Token验证成功，用户：{}", username);
            return true;

        } catch (io.jsonwebtoken.ExpiredJwtException e) {
            log.warn("Token已过期：{}", e.getMessage());
            sendErrorResponse(response, 401, "登录已过期，请重新登录");
            return false;
        } catch (io.jsonwebtoken.JwtException e) {
            log.warn("Token无效：{}", e.getMessage());
            sendErrorResponse(response, 401, "Token无效，请重新登录");
            return false;
        } catch (Exception e) {
            log.error("Token验证失败：{}", e.getMessage(), e);
            sendErrorResponse(response, 401, "Token验证失败，请重新登录");
            return false;
        }
    }

    /**
     * 设置CORS响应头
     */
    private void setCorsHeaders(HttpServletRequest request, HttpServletResponse response) {
        String origin = request.getHeader("Origin");
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
    }

    /**
     * 请求完成后清理ThreadLocal，防止内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.clearContext();
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, int code, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        Result<Object> result = Result.error(code, message);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(result);
        
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
}

